// 游戏配置
const CONFIG = {
    canvas: {
        width: 800,
        height: 600
    },
    game: {
        speed: 5,
        speedIncrease: 0.001,
        maxSpeed: 15,
        gravity: 0.5,
        jumpPower: -12,
        lanes: 3,
        laneWidth: 200
    },
    player: {
        width: 40,
        height: 60,
        x: 100,
        y: 400
    },
    obstacles: {
        train: { width: 100, height: 80, color: '#FF4444' },
        barrier: { width: 40, height: 60, color: '#4444FF' },
        coin: { width: 30, height: 30, color: '#FFD700' },
        powerup: { width: 40, height: 40, color: '#00FF00' }
    }
};

// 游戏状态
let gameState = {
    isRunning: false,
    isPaused: false,
    score: 0,
    highScore: localStorage.getItem('subwayHighScore') || 0,
    speed: CONFIG.game.speed,
    gravity: CONFIG.game.gravity,
    jumpPower: CONFIG.game.jumpPower
};

// 玩家对象
let player = {
    x: CONFIG.player.x,
    y: CONFIG.player.y,
    width: CONFIG.player.width,
    height: CONFIG.player.height,
    velocityY: 0,
    isJumping: false,
    isSliding: false,
    slideTimer: 0,
    lane: 1, // 0, 1, 2 对应三条轨道
    invincible: false,
    invincibleTimer: 0
};

// 游戏对象数组
let obstacles = [];
let coins = [];
let powerups = [];
let particles = [];

// Canvas 和上下文
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');

// DOM 元素
const scoreElement = document.getElementById('score');
const highScoreElement = document.getElementById('high-score');
const pauseBtn = document.getElementById('pause-btn');
const restartBtn = document.getElementById('restart-btn');
const gameOverModal = document.getElementById('gameOverModal');
const finalScoreElement = document.getElementById('final-score');
const modalHighScoreElement = document.getElementById('modal-high-score');
const restartGameBtn = document.getElementById('restart-game-btn');

// 初始化游戏
function init() {
    highScoreElement.textContent = gameState.highScore;
    bindEvents();
    resetGame();
    gameLoop();
}

// 绑定事件
function bindEvents() {
    document.addEventListener('keydown', handleKeyPress);
    pauseBtn.addEventListener('click', togglePause);
    restartBtn.addEventListener('click', resetGame);
    restartGameBtn.addEventListener('click', resetGame);
}

// 键盘事件处理
function handleKeyPress(e) {
    if (!gameState.isRunning || gameState.isPaused) return;

    switch(e.key) {
        case 'ArrowLeft':
            movePlayer(-1);
            break;
        case 'ArrowRight':
            movePlayer(1);
            break;
        case 'ArrowUp':
            jump();
            break;
        case 'ArrowDown':
            slide();
            break;
    }
}

// 移动玩家
function movePlayer(direction) {
    player.lane = Math.max(0, Math.min(2, player.lane + direction));
    player.x = 100 + player.lane * CONFIG.game.laneWidth;
}

// 跳跃
function jump() {
    if (!player.isJumping && !player.isSliding) {
        player.velocityY = CONFIG.game.jumpPower;
        player.isJumping = true;
    }
}

// 下滑
function slide() {
    if (!player.isJumping && !player.isSliding) {
        player.isSliding = true;
        player.slideTimer = 30;
        player.height = CONFIG.player.height / 2;
        player.y += CONFIG.player.height / 2;
    }
}

// 切换暂停
function togglePause() {
    gameState.isPaused = !gameState.isPaused;
    pauseBtn.textContent = gameState.isPaused ? '继续' : '暂停';
}

// 重置游戏
function resetGame() {
    gameState.score = 0;
    gameState.speed = CONFIG.game.speed;
    gameState.isRunning = true;
    gameState.isPaused = false;
    
    player.x = CONFIG.player.x;
    player.y = CONFIG.player.y;
    player.velocityY = 0;
    player.isJumping = false;
    player.isSliding = false;
    player.lane = 1;
    player.invincible = false;
    player.height = CONFIG.player.height;
    
    obstacles = [];
    coins = [];
    powerups = [];
    particles = [];
    
    gameOverModal.classList.add('hidden');
    pauseBtn.textContent = '暂停';
}

// 生成障碍物
function spawnObstacle() {
    if (Math.random() < 0.02) {
        const lane = Math.floor(Math.random() * CONFIG.game.lanes);
        const x = 100 + lane * CONFIG.game.laneWidth;
        
        if (Math.random() < 0.7) {
            // 生成列车
            obstacles.push({
                x: x,
                y: 400,
                width: CONFIG.obstacles.train.width,
                height: CONFIG.obstacles.train.height,
                type: 'train',
                color: CONFIG.obstacles.train.color
            });
        } else {
            // 生成路障
            obstacles.push({
                x: x,
                y: 420,
                width: CONFIG.obstacles.barrier.width,
                height: CONFIG.obstacles.barrier.height,
                type: 'barrier',
                color: CONFIG.obstacles.barrier.color
            });
        }
    }
}

// 生成金币
function spawnCoin() {
    if (Math.random() < 0.03) {
        const lane = Math.floor(Math.random() * CONFIG.game.lanes);
        const x = 100 + lane * CONFIG.game.laneWidth;
        
        coins.push({
            x: x,
            y: 350 + Math.random() * 100,
            width: CONFIG.obstacles.coin.width,
            height: CONFIG.obstacles.coin.height,
            collected: false
        });
    }
}

// 生成道具
function spawnPowerup() {
    if (Math.random() < 0.005) {
        const lane = Math.floor(Math.random() * CONFIG.game.lanes);
        const x = 100 + lane * CONFIG.game.laneWidth;
        
        powerups.push({
            x: x,
            y: 380,
            width: CONFIG.obstacles.powerup.width,
            height: CONFIG.obstacles.powerup.height,
            type: 'invincible',
            collected: false
        });
    }
}

// 更新游戏状态
function update() {
    if (!gameState.isRunning || gameState.isPaused) return;

    // 增加速度
    gameState.speed = Math.min(CONFIG.game.maxSpeed, gameState.speed + CONFIG.game.speedIncrease);

    // 更新玩家物理
    if (player.isJumping) {
        player.velocityY += CONFIG.game.gravity;
        player.y += player.velocityY;
        
        if (player.y >= CONFIG.player.y) {
            player.y = CONFIG.player.y;
            player.velocityY = 0;
            player.isJumping = false;
        }
    }

    // 更新下滑状态
    if (player.isSliding) {
        player.slideTimer--;
        if (player.slideTimer <= 0) {
            player.isSliding = false;
            player.height = CONFIG.player.height;
            player.y = CONFIG.player.y;
        }
    }

    // 更新无敌状态
    if (player.invincible) {
        player.invincibleTimer--;
        if (player.invincibleTimer <= 0) {
            player.invincible = false;
        }
    }

    // 更新障碍物位置
    obstacles.forEach(obstacle => {
        obstacle.x -= gameState.speed;
    });

    // 更新金币位置
    coins.forEach(coin => {
        coin.x -= gameState.speed;
    });

    // 更新道具位置
    powerups.forEach(powerup => {
        powerup.x -= gameState.speed;
    });

    // 移除屏幕外的对象
    obstacles = obstacles.filter(obstacle => obstacle.x + obstacle.width > 0);
    coins = coins.filter(coin => coin.x + coin.width > 0);
    powerups = powerups.filter(powerup => powerup.x + powerup.width > 0);

    // 生成新对象
    spawnObstacle();
    spawnCoin();
    spawnPowerup();

    // 碰撞检测
    checkCollisions();

    // 更新分数
    gameState.score += Math.floor(gameState.speed / 10);
    scoreElement.textContent = gameState.score;
}

// 碰撞检测
function checkCollisions() {
    // 检测与障碍物的碰撞
    obstacles.forEach(obstacle => {
        if (isColliding(player, obstacle) && !player.invincible) {
            gameOver();
        }
    });

    // 检测与金币的碰撞
    coins.forEach(coin => {
        if (!coin.collected && isColliding(player, coin)) {
            coin.collected = true;
            gameState.score += 50;
            createParticles(coin.x, coin.y, '#FFD700');
        }
    });

    // 检测与道具的碰撞
    powerups.forEach(powerup => {
        if (!powerup.collected && isColliding(player, powerup)) {
            powerup.collected = true;
            if (powerup.type === 'invincible') {
                player.invincible = true;
                player.invincibleTimer = 300; // 5秒无敌
            }
        }
    });
}

// 碰撞检测辅助函数
function isColliding(a, b) {
    return a.x < b.x + b.width &&
           a.x + a.width > b.x &&
           a.y < b.y + b.height &&
           a.y + a.height > b.y;
}

// 创建粒子效果
function createParticles(x, y, color) {
    for (let i = 0; i < 5; i++) {
        particles.push({
            x: x,
            y: y,
            vx: (Math.random() - 0.5) * 5,
            vy: (Math.random() - 0.5) * 5,
            life: 30,
            color: color
        });
    }
}

// 渲染游戏
function render() {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 绘制背景
    drawBackground();

    // 绘制轨道
    drawTracks();

    // 绘制玩家
    drawPlayer();

    // 绘制障碍物
    obstacles.forEach(obstacle => {
        ctx.fillStyle = obstacle.color;
        ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
    });

    // 绘制金币
    coins.forEach(coin => {
        if (!coin.collected) {
            ctx.fillStyle = CONFIG.obstacles.coin.color;
            ctx.beginPath();
            ctx.arc(coin.x + coin.width/2, coin.y + coin.height/2, coin.width/2, 0, Math.PI * 2);
            ctx.fill();
        }
    });

    // 绘制道具
    powerups.forEach(powerup => {
        if (!powerup.collected) {
            ctx.fillStyle = CONFIG.obstacles.powerup.color;
            ctx.fillRect(powerup.x, powerup.y, powerup.width, powerup.height);
        }
    });

    // 绘制粒子效果
    particles.forEach(particle => {
        ctx.fillStyle = particle.color;
        ctx.globalAlpha = particle.life / 30;
        ctx.fillRect(particle.x, particle.y, 5, 5);
        ctx.globalAlpha = 1;
    });

    // 更新粒子
    particles = particles.filter(particle => {
        particle.x += particle.vx;
        particle.y += particle.vy;
        particle.life--;
        return particle.life > 0;
    });
}

// 绘制背景
function drawBackground() {
    const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
    gradient.addColorStop(0, '#87CEEB');
    gradient.addColorStop(1, '#98FB98');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
}

// 绘制轨道
function drawTracks() {
    ctx.strokeStyle = '#333';
    ctx.lineWidth = 3;
    
    for (let i = 0; i <= CONFIG.game.lanes; i++) {
        const x = 100 + i * CONFIG.game.laneWidth;
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, canvas.height);
        ctx.stroke();
    }
}

// 绘制玩家
function drawPlayer() {
    if (player.invincible && Math.floor(Date.now() / 100) % 2) {
        ctx.globalAlpha = 0.5;
    }
    
    ctx.fillStyle = '#FF6B6B';
    ctx.fillRect(player.x, player.y, player.width, player.height);
    
    // 绘制眼睛
    ctx.fillStyle = '#000';
    ctx.fillRect(player.x + 10, player.y + 10, 5, 5);
    ctx.fillRect(player.x + 25, player.y + 10, 5, 5);
    
    ctx.globalAlpha = 1;
}

// 游戏结束
function gameOver() {
    gameState.isRunning = false;
    
    if (gameState.score > gameState.highScore) {
        gameState.highScore = gameState.score;
        localStorage.setItem('subwayHighScore', gameState.highScore);
        highScoreElement.textContent = gameState.highScore;
    }
    
    finalScoreElement.textContent = gameState.score;
    modalHighScoreElement.textContent = gameState.highScore;
    gameOverModal.classList.remove('hidden');
}

// 游戏主循环
function gameLoop() {
    update();
    render();
    requestAnimationFrame(gameLoop);
}

// 启动游戏
init();
